package demo.Thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/10-08-10-22:59
 * @Description：demo.Thread    runnable创建线程
 */
public class thread_runnable {
    public static void main(String[] args) {
        Runnable buyer = new Thread_buyA();
        Thread customer1 = new Thread(buyer, "customer1");
        Thread customer2 = new Thread(buyer, "customer2");
        customer1.start();
        customer2.start();
        for (int i = 0; i < 10; i++) {
//            try {
//                Thread.sleep();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            System.out.println(customer2.getState());
        }

    }
}
class Thread_buyA implements Runnable{
    private int count = 50;
    private ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "hello");

        buy();
    }

    private void buy() {
        System.out.println(Thread.currentThread().getName() + "hello");
//        while(true){
//            lock.lock();
//            try{
//                if (count > 0){
//                    System.out.println(Thread.currentThread().getName() + "正在购买第 " + count + " 个苹果");
//                    count--;
//                } else{
//                    break;
//                }
//            }finally {
//                lock.unlock();
//                System.out.println("释放锁");
//            }
//        }

        while(true){
            synchronized (this){
                if (count > 0){
                    System.out.println(Thread.currentThread().getName() + "正在购买第 " + count + " 个苹果");
                    count--;
                }else{
                    break;
                }
            }
        }
    }
}